#!/usr/bin/perl -w

#####################################################################
# Program Variables - Go see the central config.pm!
#####################################################################
use FindBin qw($Bin);
use lib "$Bin/..";
use config;
use layout;

#####################################################################
# Program Modules
#####################################################################
# CGI Modules
use CGI;
use CGI::Carp;
use CGI::Pretty;

# Database Modules
use DBI;

# Data::Dumper for debugging
#use Data::Dumper;

# POSIX Stuff...
use POSIX;

#####################################################################
# Program Start
#####################################################################
my $cgi = new CGI;

my $pagetitle = &read_config_option("tank_name") . " Graph Line Configuration";

# Web Page output
&ts_pagestart($pagetitle);

# Parameter List Checking
my %params = $cgi->Vars;

foreach $key (keys %params) {
    print $cgi->comment("$key") . "\n";

    if ($key eq "add_line") {
        &edit_test(undef);
    } elsif ($key eq "write_line") {
        &write_line(%params);
    } elsif ($key =~ /edit_(.*)/i) {
        &edit_test($1);
    } elsif ($key =~ /delete_(.*)/i) {
        &delete_test($1);
    }
}

#######################################
# Get the most recent statistics

my @tablerows;
push(@tablerows, $cgi->th([ "Graph", "Line Position", "Line Colour", "&nbsp;" ]));

my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");

# Collate the most recent data.
my $test_sth = $dbh->prepare("SELECT ROWID,* FROM graphlines ORDER BY graphname,lineposition ASC");
$test_sth->execute();
while (my $testref = $test_sth->fetchrow_hashref()) {
    my %linehash = %{$testref};

    push(
        @tablerows,
        $cgi->td([
                $linehash{graphname},
                $linehash{lineposition},
                $linehash{linecolour},
                $cgi->submit(-name => "edit_$linehash{rowid}", -label => "Edit") . " | "
                  . $cgi->submit(-name => "delete_$linehash{rowid}", -label => "Delete") ]));
}

push(@tablerows, $cgi->td({ colspan => "4" }, $cgi->submit(-name => "add_line", -label => "Add Graph Line")));

# Close the database
$test_sth->finish;
$dbh->disconnect;
#######################################

# Start the forms
print $cgi->start_form;
print $cgi->start_table({ -align => 'center' });
print $cgi->Tr([@tablerows]);
print $cgi->end_table;
print $cgi->end_form;
print $cgi->p($cgi->center("Return to the " . $cgi->a({ -href => "./" }, &read_config_option("tank_name") . " Configuration Index") . " Page."));
print $cgi->end_html;
print "\n";
exit 0;

#####################################################################
# Program Subroutines
#####################################################################
sub edit_test {
    my $lineid = shift @_;
    my %linehash;

    my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");
    if (defined($lineid)) {
        my $testref = $dbh->selectrow_hashref("SELECT * FROM graphlines WHERE ROWID=?", undef, $lineid);
        if (defined($testref)) {
            %linehash = %{$testref};
        }
    }

    my @graphnames = @{ $dbh->selectcol_arrayref("SELECT DISTINCT name FROM tests ORDER BY name") };

    $dbh->disconnect();

    # Start the forms
    print $cgi->start_form;
    if (defined($lineid)) {
        print $cgi->hidden(-name => "lineid", -value => $lineid);
    }

    print $cgi->start_table({ -align => 'center' });
    print $cgi->Tr([
            $cgi->th({ -class => "right" }, ["Graph Name"])

              #. $cgi->td({ -class => "left" }, [ $cgi->textfield(-name => "graphname", -default => $linehash{graphname} || "", -size => "20") ]) ]);
              . $cgi->td(
                { -class => "left" },
                [ $cgi->popup_menu(-name => "graphname", -values => [@graphnames], -default => ($linehash{graphname} || "")) ]) ]);
    print $cgi->Tr([
                $cgi->th({ -class => "right" }, ["Line Position"])
              . $cgi->td({ -class => "left" }, [ $cgi->textfield(-name => "lineposition", -default => $linehash{lineposition} || "", -size => "5") ])
        ]);
    print $cgi->Tr([
                $cgi->th({ -class => "right" }, ["Line Colour"])
              . $cgi->td({ -class => "left" }, [ $cgi->textfield(-name => "linecolour", -default => $linehash{linecolour} || "", -size => "50") ]) ]);
    print $cgi->Tr([
            $cgi->td(
                { -colspan => "2" },
                [ $cgi->submit(-name => "write_line", -label => "Save") . " | " . $cgi->reset . " | " . $cgi->a({ -href => "graphs.cgi" }, "Back") ])
        ]);
    print $cgi->end_table;
    print $cgi->end_form;
    print $cgi->end_html;
    print "\n";
    exit 0;

}

# Write/Upoate the test to the database
sub write_line {
    my %cgiparams = @_;
    my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");
    if (defined($cgiparams{lineid})) {

        # If given the row id, then we are updating the database
        $dbh->do(
            "UPDATE graphlines SET graphname=?, lineposition=?, linecolour=? WHERE ROWID=?",
            undef, $cgiparams{graphname}, $cgiparams{lineposition},
            $cgiparams{linecolour}, $cgiparams{lineid});
    } else {

        # Otherwise we are adding a new record
        $dbh->do(
            "INSERT INTO graphlines (graphname, lineposition, linecolour) VALUES (?, ?, ?)",
            undef, $cgiparams{graphname}, $cgiparams{lineposition},
            $cgiparams{linecolour});
    }

    # Close the database
    $dbh->disconnect;

    print $cgi->comment("Entry Added/Updated"), "\n";
    $cgi->delete_all();
    return;
}

# Delete the selected test from the database
sub delete_test {
    my $entry = shift @_;

    # Open the database
    my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");

    # Delete the record
    $dbh->do("DELETE FROM graphlines WHERE ROWID=?", undef, $entry);

    # Close the database
    $dbh->disconnect;

    print $cgi->comment("Entry Deleted"), "\n";
    $cgi->delete_all();
    return;
}

